﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Qizx.Api;
using System.Qizx.XQuery;
using System.Qizx.XQuery.Fn;
using System.Qizx.XQuery.Dt;

namespace System.Qizx.XQuery.Op {
    class FunctionLiteral : Expression
{
    QName name;
    int   arity;
    Prototype proto;
    
    public FunctionLiteral(QName fname, long arity)
    {
        this.name = fname;
        this.arity = (int) arity;
    }

    public override Expression Child(int rank) {
        return null;
    }

    public void dump(ExprDisplay d)
    {
        d.header(this);
        d.property("value", toString());
    }

    public String toString()
    {
        return name + "#" + arity + " " + proto;
    }

    public int getFlags() {
        return CONSTANT;
    }

    public override Expression StaticCheck(ModuleContext context, int flags)
    {
        proto = context.functionLookup(name, arity);
        if (proto == null) {
            context.error("XPST0017", this,
                          "no function '" + context.PrefixedName(name)
                          + "' accepting " + arity + " arguments");
            return this;
        }
        setType(new FunctionType(proto));
        return this;
    }

    public override
        XQValue eval(Focus focus, EvalContext context)
    {
        return new FunctionItem(proto, context);
    }

    public override XQItem evalAsItem(Focus focus, EvalContext context)
    {        
        return new FunctionItem(proto, context);
    }
}
}